package com.hyfrogx.modules.manage.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.common.utils.StringTokenizerUtils;
import com.hyfrogx.modules.manage.dao.HyFlashLiveDao;
import com.hyfrogx.modules.manage.entity.CoindogLiveEntity;
import com.hyfrogx.modules.manage.entity.HyFlashTypeEntity;
import com.hyfrogx.modules.manage.form.coindog.CoindogList;
import com.hyfrogx.modules.manage.form.flash.FlashVo;
import com.hyfrogx.modules.manage.service.HyFlashLiveService;
import com.hyfrogx.modules.manage.service.HyFlashTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version 1.0.0
 * @Author: lfh
 * @Date: 2019/9/27 15:38
 * @Company 汉咏科技
 */
@Service
public class HyFlashLiveServiceImpl extends ServiceImpl<HyFlashLiveDao, CoindogLiveEntity> implements HyFlashLiveService {

    @Autowired
    private HyFlashTypeService hyFlashTypeService;

    /**
     * 数据库的最新的快讯 flash_id
     */
    private  static Long maxID = 0L;
    /**
     * 数据库的最新的第十条（可能没有10条）的flash_id
     */
    private  static Long minID = 0L;

    /**
     *时间戳转换时间
     */
    public Date LongtoDate(Long crated_at)
    {
        return DateUtil.date(crated_at*1000);
    }

    /**
     * 发布时间创建
     * @return
     */
    public String DateToString(Date date)
    {
        String strDate = null;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd EE HH:mm");
        strDate = dateFormat.format(date);
        return strDate;
    }

    /**
     *分类，标题，内容分段
     * @return
     */
    public String[] split(String content)
    {
        //定义返回的3个字符，0：类型；1：标题；2：内容；
        String[] result =new String[3];
        //分割并保存末尾的内容
        String[] strings= StringTokenizerUtils.split(content,"】");
        result[2] = strings[strings.length-1].trim();
        //分割并保存末尾的标题
        String[] strings1 = StringTokenizerUtils.split(strings[0],"|");
        result[1] = strings1[strings1.length-1].trim();
        //分割并保存末尾的类型
        String[] strings2 = StringTokenizerUtils.split(strings1[0],"【");
        result[0] = strings2[strings2.length-1].trim();
        return  result;
    }


    @Override
    public R getCoindog() {
        //获取数据库中最新一条快讯的id
        CoindogLiveEntity shortCoindogLiveEntity = this.getOne(new QueryWrapper<CoindogLiveEntity>().orderByDesc("flash_id").last("LIMIT 1"));
        if (ObjectUtil.isNotNull(shortCoindogLiveEntity))
        {
            maxID = shortCoindogLiveEntity.getFlashId();
        }

        //设置请求条件
        Map map = new HashMap();
        //每次请求条数
        map.put("limit",10);
        //快讯id，（注意，依然会返回小于id的数据）
        map.put("id",maxID);
        //设置获取最新快讯
        map.put("flag","up");
        //发出请求，获取快讯数据
        String result = HttpUtil.get("http://api.coindog.com/live/list",map);
        JSONObject jsonObject = JSON.parseObject(result);
        //获取JSON中的list数组
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        //定义一个CoindogList数组，存储转换后的CoindogList
        List<CoindogList> coindogLists = new ArrayList<>();
        //创建JSON中list数组的迭代器，遍历CoindongList对象，CoindongList包含一个日期和一个快讯集合
        Iterator<Object> iterator = jsonArray.iterator();

        while (iterator.hasNext())
        {
//            使用alibaba.fastjson工具类
//            便利数组，把对象转换成JSON字符串，再把JSON字符串转换成JSONObject，再把JSONObject对象转换成CoindogList对象，添加到数组
            JSONObject object = JSON.parseObject(JSON.toJSONString(iterator.next()));
            coindogLists.add(object.toJavaObject(CoindogList.class));
        }

        //获取数据库中最新10条记录的flash_id
        Long[] flash_ids = this.baseMapper.getTenFlashIds();
        if (ArrayUtil.isNotEmpty(flash_ids))
        {
            minID = flash_ids[flash_ids.length-1];
        }

        //获取数据库的所有快讯分类
        List<HyFlashTypeEntity>  flashTypeEntityList = hyFlashTypeService.list();
        Map<String,Integer> flashTypeMap = new HashMap();
        for (HyFlashTypeEntity hyFlashTypeEntity:flashTypeEntityList)
        {
            flashTypeMap.put(hyFlashTypeEntity.getTypeName(),hyFlashTypeEntity.getId());
        }

        //如果有多个日期。将多个日期倒转
        Collections.reverse(coindogLists);
        //存储快讯
        for (CoindogList coindogList:coindogLists)
        {
            //对CoinDogLive的date时间赋值
            Date date = coindogList.getDate();
            //遍历同一时间的快讯集合
            Iterator<CoindogLiveEntity> liveiterator = coindogList.getLives().iterator();
            while (liveiterator.hasNext())
            {
                CoindogLiveEntity coindogLiveEntity = liveiterator.next();
                //如果新获取的10条快讯中id有小于数据库的最新第十条id 或者 数据库中已经存在，则移除；
                if (coindogLiveEntity.getFlashId()<=minID || ArrayUtil.contains(flash_ids,coindogLiveEntity.getFlashId()))
                {
                    liveiterator.remove();
                }
                else
                {
                    //对内容进行分割，分割成类型,标题和文章内容
                    String[] results = split(coindogLiveEntity.getContent());
                    //设置分类,如果该快讯有分类
                    if (flashTypeMap.containsKey(results[0]))
                    {
                        coindogLiveEntity.setTypeId(flashTypeMap.get(results[0]));
                    }
                    coindogLiveEntity.setTypeName(results[0]);

                    //设置标题
                    coindogLiveEntity.setTitle(results[1]);
                    //设置文章内容
                    coindogLiveEntity.setContent(results[2]);
                    //设置JSON总时间
                    coindogLiveEntity.setDate(date);
                    //设置快讯的获取时间
                    coindogLiveEntity.setCreatetime(new Date());
                    //设置快讯接口中的时间
                    coindogLiveEntity.setCreatedTime(LongtoDate(coindogLiveEntity.getCreatedAt()));
                }
            }
            //如果存在快讯，则进行插入操纵
            if (coindogList.getLives().size()>0) {
                //将每个日期的快讯集合元素倒转
                Collections.reverse(coindogList.getLives());
                this.baseMapper.saveFlashList(coindogList.getLives());
            }
        }
        return R.ok().put("resutl",coindogLists);
    }

    @Override
    public IPage<FlashVo> getByPageFromSql(QueryExt queryExt, Map map) {
        List<FlashVo> liveEntities = this.baseMapper.getByPageFromSql(queryExt,map);
        queryExt.setRecords(liveEntities);
        return queryExt;
    }

    @Override
    public Boolean updateLiveOne(CoindogLiveEntity coindogLiveEntity) {
        //判断本次编辑是否有上架操作
        IsOrNotRelease(coindogLiveEntity);
        //更改分类
        if (ObjectUtil.isNotNull(coindogLiveEntity.getTypeId()))
        {
            Integer typeId = coindogLiveEntity.getTypeId();
            String typeName = hyFlashTypeService.getById(typeId).getTypeName();
            coindogLiveEntity.setTypeName(typeName);
        }
        return this.updateById(coindogLiveEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateLiveList(List<CoindogLiveEntity> coindogLiveEntities) {
        return this.updateBatchById(coindogLiveEntities);
    }

    @Override
    public Boolean updateStatusOne(Long id) {
        //通过id获取快讯状态
        CoindogLiveEntity coindogLiveEntity = this.getById(id);
        Integer status = coindogLiveEntity.getStatus();
        //状态转换
        status = status==1 ? 0:1;
        coindogLiveEntity.setId(id);
        coindogLiveEntity.setStatus(status);
        //判断是否为上架操作
        IsOrNotRelease(coindogLiveEntity);
        return this.updateById(coindogLiveEntity);

    }
    public void IsOrNotRelease(CoindogLiveEntity coindogLiveEntity)
    {
        if (ObjectUtil.isNotNull(coindogLiveEntity.getStatus()) && coindogLiveEntity.getStatus()==1)
        {
            coindogLiveEntity.setReleasetime(DateToString(new Date()));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void LiveUpList(Long[] id) {
        try{
            //快讯上架时间
            String releaseTime =DateToString(new Date());
            //更新快讯状态为上架
            this.baseMapper.LiveUpList(id,releaseTime);
        }
        catch(MyException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new MyException("批量发布异常失败");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void LiveDownList(Long[] id) {
        try{
            //更新快讯状态为上架
            this.baseMapper.LiveDownList(id);
        }
        catch(MyException e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new MyException("批量下架异常失败");
        }
    }

    @Override
    public Boolean deleteLiveOne(Long id) {
        return this.removeById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteLiveList(Long[] id) {

        try{
            this.baseMapper.DeleteLiveList(id);
        }catch (MyException e)
        {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new MyException("批量删除异常失败");
        }

    }



}
